﻿using System.IO;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Utilities;

namespace SPContrib.SharePoint.Extensions
{
    /// <summary>
    /// Extensions for the FileInfo class
    /// </summary>
    public static class FileInfoExtensions
    {
        private static readonly Regex SPResourceRegex = new Regex(@"(\$Resources\:(?<resx>[^,;]+),(?<key>[^;]+);)|(\$Resources\:(?<key>[^;]+);)", RegexOptions.Compiled);

        /// <summary>
        /// Returns a localized string that represents the FileInfo (i.e. uses SPUtility.GetLocalizedString on each $Resource found)
        /// </summary>
        public static string AsLocalizedString(this FileInfo instance)
        {
            string text = string.Empty;
            uint lcid = 1033; // TODO: fix language from feature

            using (StreamReader sr = instance.OpenText())
            {
                text = sr.ReadToEnd();
            }

            string localized = SPResourceRegex.Replace(text, match =>
            {
                var resx = match.Groups["resx"];
                var key = match.Groups["key"];

                if (resx.Success)
                {
                    return SPUtility.GetLocalizedString(key.Value, resx.Value, lcid);
                }
                else
                {
                    // TODO: ?? feature resx?
                    return SPUtility.GetLocalizedString(key.Value, "core", lcid);
                }
            });

            return localized;
        }
    }
}
